package com.sjy.project.fym.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Validator;

import com.sjy.common.exception.ServiceException;
import com.sjy.common.utils.DateUtils;
import com.sjy.common.utils.StringUtils;
import com.sjy.common.utils.bean.BeanValidators;
import com.sjy.common.utils.security.ShiroUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sjy.project.fym.user.mapper.FyUserMapper;
import com.sjy.project.fym.place.domain.FyPlace;
import com.sjy.project.fym.team.domain.FyTeam;
import com.sjy.project.fym.team.mapper.FyTeamMapper;
import com.sjy.project.fym.user.domain.FyUser;
import com.sjy.project.fym.user.domain.FyUser;
import com.sjy.project.fym.user.service.IFyUserService;
import com.sjy.project.system.user.service.UserServiceImpl;
import com.sjy.common.utils.text.Convert;
import com.sjy.framework.web.domain.Ztree;

/**
 * 防疫人员信息Service业务层处理
 * 
 * @author sjy
 * @date 2022-04-18
 */
@Service
public class FyUserServiceImpl implements IFyUserService 
{
	private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private FyUserMapper fyUserMapper;
    @Autowired
    private FyTeamMapper fyTeamMapper;
    @Autowired
    protected Validator validator;

    /**
     * 查询防疫人员信息
     * 
     * @param userId 防疫人员信息主键
     * @return 防疫人员信息
     */
    @Override
    public FyUser selectFyUserByUserId(Long userId)
    {
        return fyUserMapper.selectFyUserByUserId(userId);
    }

    /**
     * 查询防疫人员信息列表
     * 
     * @param fyUser 防疫人员信息
     * @return 防疫人员信息
     */
    @Override
    public List<FyUser> selectFyUserList(FyUser fyUser)
    {
        return fyUserMapper.selectFyUserList(fyUser);
    }
    /**
     *批量场所Ids获取userNames
     * 
     * @param userIds 防疫人员信息主键
     * @return 防疫人员信息
     */
    public String selectFyUserNamesByUserIds(String userIds) {
    	return fyUserMapper.selectFyUserNamesByUserIds(userIds);
    }
    /**
     * 新增防疫人员信息
     * 
     * @param fyUser 防疫人员信息
     * @return 结果
     */
    @Override
    public int insertFyUser(FyUser fyUser)
    {
        fyUser.setCreateTime(DateUtils.getNowDate());
        return fyUserMapper.insertFyUser(fyUser);
    }

    /**
     * 修改防疫人员信息
     * 
     * @param fyUser 防疫人员信息
     * @return 结果
     */
    @Override
    public int updateFyUser(FyUser fyUser)
    {
        fyUser.setUpdateTime(DateUtils.getNowDate());
        return fyUserMapper.updateFyUser(fyUser);
    }
    
    /**
     * 批量更新 人员归属队伍
     * @param teamId
     * @param userIds
     * @return
     */
    public int updateFyUserIds(Long teamId,String userIds) {
    	int i = 0;
    	for(String userId:userIds.split(",")) {
    		FyUser fyUser = fyUserMapper.selectFyUserByUserId(Long.parseLong(userId));
        	fyUser.setUpdateTime(DateUtils.getNowDate());
        	fyUser.setTeamId(teamId);
        	fyUserMapper.updateFyUser(fyUser);
        	i++;
    	}
        return i;
    }

    /**
     * 批量删除防疫人员信息
     * 
     * @param userIds 需要删除的防疫人员信息主键
     * @return 结果
     */
    @Override
    public int deleteFyUserByUserIds(String userIds)
    {
        return fyUserMapper.deleteFyUserByUserIds(Convert.toStrArray(userIds));
    }

    /**
     * 删除防疫人员信息信息
     * 
     * @param userId 防疫人员信息主键
     * @return 结果
     */
    @Override
    public int deleteFyUserByUserId(Long userId)
    {
        return fyUserMapper.deleteFyUserByUserId(userId);
    }
    /**
     * 查询数据是否存在
     * @param phonenumber
     * @param openId
     * @return
     */
    public FyUser selectFyUser(String phonenumber,String openId) {
    	return fyUserMapper.selectFyUser(phonenumber,openId);
    }

    /**
     * 通过手机号查询防疫人员
     * 
     * @param phonenumber 手机号码
     * @return 防疫人员对象信息
     */
    public FyUser selectUserByPhonenumber(String phonenumber) {
    	return fyUserMapper.selectUserByPhonenumber(phonenumber);
    }
    /**
     * 导入防疫人员数据
     * 
     * @param userList 人员数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importUser(List<FyUser> userList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入人员数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String operName = ShiroUtils.getLoginName();
        for (FyUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                FyUser u = fyUserMapper.selectUserByPhonenumber(user.getPhonenumber());
                FyTeam t = fyTeamMapper.selectTeamByTeamName(user.getTeamName());
                if(StringUtils.isNull(t)) {
                	failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、手机号码 " + user.getPhonenumber() + " 对应防疫队伍 "+t.getTeamName()+"不存在");
                
                }else {
	                if (StringUtils.isNull(u))
	                {
	                    BeanValidators.validateWithException(validator, user);
	                    user.setCreateBy(operName);
	                    user.setTeamId(t.getTeamId());
	                    this.insertFyUser(user);
	                    successNum++;
	                    successMsg.append("<br/>" + successNum + "、手机号码 " + user.getPhonenumber() + " 导入成功");
	                }
	                else if (isUpdateSupport)
	                {
	                    BeanValidators.validateWithException(validator, user);
	                    user.setUserId(u.getUserId());
	                    user.setUpdateBy(operName);
	                    this.updateFyUser(user);
	                    successNum++;
	                    successMsg.append("<br/>" + successNum + "、手机号码 " + user.getPhonenumber() + " 更新成功");
	                }
	                else
	                {
	                    failureNum++;
	                    failureMsg.append("<br/>" + failureNum + "、手机号码 " + user.getPhonenumber() + " 已存在");
	                }
	            }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、手机号码 " + user.getPhonenumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    

    /**
     * 查人员管理树
     * @param fyUser 人员信息
     * @return 所有人员信息
     */
    @Override
    public List<Ztree> selectUserTree(FyUser fyUser,Long teamId,boolean checked)
    {
        List<FyUser> userList = fyUserMapper.selectFyUserList(fyUser);
        List<Ztree> ztrees = initZtree(userList,teamId,checked);
        return ztrees;
    }
    
    /**
     * 对象转部门树
     *
     * @param placeList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<FyUser> usreList,Long teamId,boolean checked)
    {
    	List<Long> roleDeptList = new ArrayList<Long>();
    	if(checked) {
    		roleDeptList.add(teamId);
    	}
        return initZtree(usreList, roleDeptList);
    }

    /**
     * 对象转部门树
     *
     * @param placeList 部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<FyUser> userList, List<Long> roleDeptList)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (FyUser fyUser : userList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(fyUser.getUserId());
            ztree.setpId(null);
            ztree.setName(fyUser.getUserName()+" "+(fyUser.getTeamName()==null?"":fyUser.getTeamName())+' '+fyUser.getPhonenumber());
            ztree.setTitle(fyUser.getUserName());
            if (isCheck)
            {
                ztree.setChecked(roleDeptList.contains(fyUser.getTeamId()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }
}
